package org.niit.kafka;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;

public class KafkaConsumerByHandSync {

    public static void main(String[] args) {

        //1.创建Kafka消费者的连接
        Properties proprs = new Properties();
        //1.1配置连接机器的地址
        proprs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"node1:9092");
        //1.2指定消费者组
        proprs.put(ConsumerConfig.GROUP_ID_CONFIG,"P1");
        //1.3手动提交偏移量
        proprs.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false");

        //将Kafka读取的二进制数据 转换为 字符串
        proprs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        proprs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());

        //2.创建Kafka的消费者
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(proprs);

        consumer.subscribe(Arrays.asList("BD1"));

        //3.消费数据
        while (true){
                    //拉取是一批数据
            ConsumerRecords<String,String> records = consumer.poll(Duration.ofSeconds(3));

            for (ConsumerRecord<String,String> record:records) {

                String topic = record.topic();
                long offset = record.offset();
                String key = record.key();
                String value = record.value();
                System.out.println("消费主题："+topic+",偏移量："+offset+",键："+key+",值："+value);
                //手动提交的同步方式-->消费者将所有的偏移量提交到broker，broker应答后再去获取新数据
                //consumer.commitSync();

                //手动提交的异步方式 （在实际开发中用的比较多）--> 消费者将所有消费的偏移量提交到Broker,Broker无论应答成功还是失败，消费者都继续消费数据
                consumer.commitAsync(new OffsetCommitCallback() {
                    @Override
                    public void onComplete(Map<TopicPartition, OffsetAndMetadata> map, Exception e) {
                            if(e ==null ){
                                System.out.println("消费数据成功："+map);
                            }else{
                                System.out.println("消费数据失败："+e.getMessage());
                            }
                    }

                });
            }
        }
    }

}
